﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using ChanExt;
using C.Unite;
using C.Entities;

namespace ArtLand.OA.Project.Project
{
    public partial class Pro_PoDataChange : CommonPageBase
    {
        List<TempFile> files = new List<TempFile>();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //txt_ATTEND.OnClientTriggerClick = Window1.GetSaveStateReference(hid_ATTEND.ClientID, txt_ATTEND.ClientID)
                //   + Window1.GetShowReference("/PublicModel/SelectUsers.aspx", "选择人员");

                DataBaseHelper.BindDrp(Drp_PERTAX, EnumData.DataBaseEunm.TaxRate);

                DataBaseHelper.BindDrp(Drp_PATYPE, EnumData.DataBaseEunm.PATYPE);

                DataBaseHelper.BindDrp(Drp_POTYPE, EnumData.DataBaseEunm.PoData);

                FormInfo.ShowTriggerWin(Window1, txt_CONNUB, hid_A, Label12, "/PublicModel/SelectContat.aspx", "选择合同");

                FormInfo.ShowTriggerWin(Window1, txt_VEDNUB, hid_VEDNUB, "/PublicModel/SelectVend.aspx", "选择供应商");

                FormInfo.ShowTriggerWin(Window1, txt_REQTOR, hid_REQTOR, "/PublicModel/SelectUsers.aspx", "选择申请人");

                txt_AddTime.Text = DateTime.Now.ToString("yyyy-MM-dd");

                Button10.OnClientClick = ActiveWindow.GetHideReference();
                LoadData();
                BindGrid();


            }
        }

        protected void LoadData()
        {
            if (!string.IsNullOrEmpty(Request["cid"]))
            {
                Proj_Contat con = TbsDbSession.Default.From<Proj_Contat>().Where(Proj_Contat._.ID == int.Parse(Request["cid"])).ToFirst();
                txt_CONNUB.Text = con.CONNUB;
                object ob = TbsDbSession.Default.From<Proj_Podata>().Where(Proj_Podata._.CONNUB == con.CONNUB).Select(Proj_Podata._.TAMOUT.Sum()).ToScalar();
                string s = "";
                if (ob.ToString() != "")
                    s = string.Format("<b>合同的总金额为：{1}</b><br><br><span style='color:red;font-weight:bold;'>该合同的现采购合计总额为：{0}</span>", ob, con.AMOUNT.Value);
                else
                    s = string.Format("<b>合同的总金额为：{0}</b>", con.AMOUNT.Value);
                hid_A.Text = con.AMOUNT.Value.ToString() + "-" + ob.ToString();
                Label12.Text = s;
                Label15.Text = con.DLDATE;
                Label14.Text = "<br><b>合同交货日期：" + con.DLDATE + "</b>";
                SetCofit();
                Group1.Enabled = true;
            }


            if (!string.IsNullOrEmpty(Request["id"]))
            {
                Proj_Podata PoData = TbsDbSession.Default.From<Proj_Podata>().Where(Proj_Podata._.ID == int.Parse(Request["id"])).ToFirst();
                if (PoData != null)
                {
                    txt_CONNUB.Text = PoData.CONNUB;
                    txt_REMARK.Text = PoData.REMARK;
                    txt_VEDNUB.Text = PoData.VEDNUB;
                    txt_VEDNNBNo.Text = PoData.VEDNNBNo;

                    Drp_PATYPE.SelectedValue = PoData.PATYPE;
                    Drp_POTYPE.SelectedValue = PoData.POTYPE;
                    if (PoData.CAMOUT.HasValue)
                        txt_CAMOUT.Text = PoData.CAMOUT.Value.ToString();
                    if (PoData.TAMOUT.HasValue)
                        txt_TAMOUT.Text = PoData.TAMOUT.Value.ToString();
                    if (PoData.DLDATE.HasValue)
                        txt_DLDATE.Text = PoData.DLDATE.Value.ToString("yyyy-MM-dd");
                    if (PoData.PERTAX.HasValue)
                    {
                        string dc = PoData.PERTAX.Value.ToString().Replace(".00", "");
                        for (int i = 0; i < Drp_PERTAX.Items.Count; i++)
                        {
                            if (Drp_PERTAX.Items[i].Text == dc.Trim())
                            {
                                Drp_PERTAX.Items[i].Selected = true;
                                break;
                            }
                        }
                        // txt_PERTAX.Text = PoData.PERTAX.Value.ToString();
                    }
                    txt_REQTOR.Text = PoData.REQTOR;
                    if (PoData.CHKTAX.HasValue)
                    {
                        if (PoData.CHKTAX.Value)
                        {
                            // CB_CHKTAX.Enabled = true;
                            CB_CHKTAX.Checked = true;
                            Drp_PERTAX.Enabled = true;
                        }
                    }
                    hf.Text = PoData.VENDPO;
                    txt_AddTime.Text = PoData.AddTime.Value.ToString("yyyy-MM-dd");
                }
                if (!string.IsNullOrEmpty(Request["s"]))
                {
                    tool1.Hidden = false;
                    tool2.Hidden = true;
                    txt_CONNUB.Enabled = false;
                    txt_REMARK.Enabled = false;
                    txt_VEDNUB.Enabled = false;
                    txt_CAMOUT.Enabled = false;
                    txt_TAMOUT.Enabled = false;
                    txt_DLDATE.Enabled = false;
                    //txt_PERTAX.Enabled = false;
                    txt_REQTOR.Enabled = false;
                    // txt_PERTAX.Enabled = false;
                    Drp_PATYPE.Enabled = false;
                    Drp_PERTAX.Enabled = false;
                    Drp_POTYPE.Enabled = false;
                    txt_AddTime.Enabled = false;
                    // Grid1.Columns[2].Enabled = false;
                    //Grid1.Columns[0].Enabled = false;
                }
                else
                {
                    tool1.Hidden = true;
                    tool2.Hidden = false;
                }
            }
            else
            {
                tool1.Hidden = true;
                tool2.Hidden = false;
            }
        }


        protected void btnSave_Click(object sender, EventArgs e)
        {
            bool yz = true;
            string mess = "";

            if (Drp_POTYPE.SelectedValue == "一般订单")
            {
                if (txt_CONNUB.Text == "" || txt_VEDNUB.Text == "" || txt_REQTOR.Text == "")
                {
                    yz = false;
                    mess = "请选择合同编号或供应商编号！";
                }
                else
                {
                    if (txt_CAMOUT.Text == "0")
                    {
                        yz = false;
                        mess = "1";
                    }
                }
            }

            if (Drp_POTYPE.SelectedValue == "特殊订单")
            {
                if (txt_REMARK.Text == "")
                {
                    yz = false;
                    mess = "该订单为特殊订单，请输入备注信息并且字数不少于10个字！";
                }
                else
                {
                    int len = txt_REMARK.Text.Length;
                    if (len < 10)
                    {
                        yz = false;
                        mess = "输入备注的字数不能少于10个字！";
                    }
                }
            }


            if (yz)
            {
                int returnvalue = 0;
                Proj_Podata PoData = new Proj_Podata();
                if (!string.IsNullOrEmpty(Request["id"]))
                {
                    PoData.ID = int.Parse(Request["id"]);
                    PoData.Attach();
                    PoData.CONNUB = txt_CONNUB.Text;
                    PoData.VENDPO = hf.Text;
                    PoData.VEDNUB = txt_VEDNUB.Text;
                    PoData.REMARK = txt_REMARK.Text;
                    PoData.CHKTAX = CB_CHKTAX.Checked;
                    PoData.CAMOUT = Convert.ToDecimal(txt_CAMOUT.Text);
                    PoData.DLDATE = Convert.ToDateTime(txt_DLDATE.Text);
                    PoData.TAMOUT = Convert.ToDecimal(txt_TAMOUT.Text);
                    PoData.REQTOR = txt_REQTOR.Text;
                    PoData.PERTAX = Convert.ToDecimal(Drp_PERTAX.SelectedValue);
                    PoData.VEDNNBNo = txt_VEDNNBNo.Text;
                    PoData.PATYPE = Drp_PATYPE.SelectedValue;
                    // PoData.PERTAX = Convert.ToDecimal(txt_PERTAX.Text);
                    PoData.STATUS = 0;
                    PoData.AddTime = Convert.ToDateTime(txt_AddTime.Text);
                    returnvalue = TbsDbSession.Default.Update<Proj_Podata>(PoData);
                }
                else
                {
                    PoData.DeAttach();
                    PoData.CONNUB = txt_CONNUB.Text;
                    PoData.VENDPO = hf.Text;
                    PoData.VEDNUB = txt_VEDNUB.Text;
                    PoData.REMARK = txt_REMARK.Text;
                    PoData.POTYPE = Drp_POTYPE.SelectedValue;
                    string s = "";
                    if (Drp_POTYPE.SelectedValue == "特殊订单")
                    {
                        PoData.CAMOUT = Convert.ToDecimal(txt_CAMOUT.Text);
                        PoData.DLDATE = Convert.ToDateTime(txt_DLDATE.Text);
                        PoData.TAMOUT = Convert.ToDecimal(txt_TAMOUT.Text);
                        PoData.PERTAX = Convert.ToDecimal(Drp_PERTAX.SelectedValue);
                        // PoData.PERTAX = Convert.ToDecimal(txt_PERTAX.Text);
                        PoData.CHKTAX = false;
                        s = "ST";
                    }
                    else
                    {
                        PoData.CAMOUT = Convert.ToDecimal(txt_CAMOUT.Text);
                        PoData.DLDATE = Convert.ToDateTime(txt_DLDATE.Text);
                        PoData.TAMOUT = Convert.ToDecimal(txt_TAMOUT.Text);
                        PoData.PERTAX = Convert.ToDecimal(Drp_PERTAX.SelectedValue);
                        // PoData.PERTAX = Convert.ToDecimal(txt_PERTAX.Text);
                        PoData.CHKTAX = CB_CHKTAX.Checked;
                    }
                    PoData.PONBER = s + DFieldSN.SN(EnumData.DataSNEunm.采购订单号, false);
                    PoData.VENDPO = hf.Text;
                    PoData.REQTOR = txt_REQTOR.Text;
                    PoData.PATYPE = Drp_PATYPE.SelectedValue;
                    PoData.STATUS = 0;
                    PoData.AddTime = Convert.ToDateTime(txt_AddTime.Text);
                    PoData.VEDNNBNo = txt_VEDNNBNo.Text;
                    returnvalue = TbsDbSession.Default.Insert<Proj_Podata>(PoData);
                }
                if (returnvalue > 0)
                {
                    Alert.Show("更新成功！", "提示", ActiveWindow.GetHideRefreshReference());
                }
            }
            else
            {
                if (mess == "1")
                {
                    PageContext.RegisterStartupScript(Confirm.GetShowReference("采购金额为0，这样可以吗？", "提示", MessageBoxIcon.Question, "__doPostBack('Button5', '');", ""));
                }
                else
                    Alert.Show(mess);
            }
        }

        protected void filePhoto_FileSelected(object sender, EventArgs e)
        {
            if (filePhoto.HasFile)
            {
                string fileName = filePhoto.ShortFileName;
                String[] str = { "1", "2", "3", "4", "5", "6", "7" };
                fileName = fileName.Replace(":", "_").Replace(" ", "_").Replace("\\", "_").Replace("/", "_");
                fileName = DateTime.Now.Ticks.ToString() + "_" + fileName;

                filePhoto.SaveAs(Server.MapPath("~/upload/" + fileName));
                hf.Text += fileName + ";";
                // 清空文件上传组件
                filePhoto.Reset();
                BindGrid();
            }
        }

        protected void BindGrid()
        {
            List<string> ls = StringHelper.GetSubStringList(hf.Text, ';');
            foreach (string item in ls)
            {
                TempFile tf = new TempFile();
                tf.FileName = item;
                files.Add(tf);
            }
            Grid1.DataSource = files;
            Grid1.DataBind();
        }


        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Del")
            {
                string[] str = Grid1.Rows[e.RowIndex].Values;
                hf.Text = hf.Text.Replace(str[1], "");
                BindGrid();
            }
        }

        protected void Grid1_RowDataBound(object sender, GridRowEventArgs e)
        {
            e.Values[0] = "<a href=\"/upload/" + e.Values[0] + "\">" + e.Values[0] + "</a>";
        }

        protected void CHK_TAX_CheckedChanged(object sender, EventArgs e)
        {
            float ft = 0;

            if (CB_CHKTAX.Checked)
            {
                ft = float.Parse(Drp_PERTAX.SelectedValue) / 100;
                Drp_PERTAX.Enabled = true;
            }
            else
            {
                Drp_PERTAX.SelectedIndex = 1;
                Drp_PERTAX.Enabled = false;
            }

            float z = float.Parse(txt_CAMOUT.Text);
            txt_TAMOUT.Text = ((1 + ft) * z).ToString();
            SetCofit();
        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            float ft = 0;
            if (CB_CHKTAX.Checked)
                ft = float.Parse(Drp_PERTAX.SelectedValue) / 100;
            float z = float.Parse(txt_CAMOUT.Text);
            txt_TAMOUT.Text = ((1 + ft) * z).ToString();
            SetCofit();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            float ft = 0;
            if (CB_CHKTAX.Checked)
                ft = float.Parse(Drp_PERTAX.SelectedValue) / 100;
            float z = float.Parse(txt_CAMOUT.Text);
            txt_TAMOUT.Text = ((1 + ft) * z).ToString();
            SetCofit();
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            float ft = 0;
            if (CB_CHKTAX.Checked)
                ft = float.Parse(Drp_PERTAX.SelectedValue) / 100;
            float z = float.Parse(txt_TAMOUT.Text);
            txt_CAMOUT.Text = (z / (1 + ft)).ToString();
            SetCofit();
        }

        protected void SetCofit()
        {
            if (hid_A.Text != "")
            {
                List<string> ls = StringHelper.GetSubStringList(hid_A.Text, '-');
                float s = 0;
                if (txt_TAMOUT.Text != "")
                    s = float.Parse(txt_TAMOUT.Text);

                float z = float.Parse(ls[0]);///总金额
                float ts = 0;
                ts = s;
                if (ls.Count > 1)
                    ts += float.Parse(ls[1]);///已采金额
                float tt1 = ts / z;
                // Label14.Text = tt1.ToString();
                if (tt1 > 0.7)
                {
                    Alert.Show("采购的总金额已经超过了合同总金额70%，请注意毛利润。");
                }
            }
        }

        protected void Res_Click(object sender, EventArgs e)
        {
            PageContext.Refresh();
        }

        protected void Window1_Close(object sender, WindowCloseEventArgs e)
        {
            if (txt_CONNUB.Text != "")
            {
                Proj_Contat pc = TbsDbSession.Default.From<Proj_Contat>().Where(Proj_Contat._.CONNUB == txt_CONNUB.Text).ToFirst();
                Label15.Text = pc.DLDATE;
                Label14.Text = "<br><b>合同交货日期：" + pc.DLDATE + "</b>";
                SetCofit();
                Group1.Enabled = true;
            }
        }

        protected void txt_DLDATE_DateSelect(object sender, EventArgs e)
        {
            if (Label15.Text != "")
            {
                DateTime dt = Convert.ToDateTime(Label15.Text);
                DateTime dtnow = Convert.ToDateTime(txt_DLDATE.Text);
                if (dtnow > dt)
                    PageContext.RegisterStartupScript(Confirm.GetShowReference("采购订单的交货日期晚于合同的交货日期，这样可以吗？", "警告提示", MessageBoxIcon.Warning, "", "__doPostBack('Button4', '');"));
            }
        }

        protected void txt_DLDATE_TextChanged(object sender, EventArgs e)
        {

        }

        protected void Button4_Click(object sender, EventArgs e)
        {
            txt_DLDATE.Text = "";
        }

        protected void Drp_PERTAX_SelectedIndexChanged(object sender, EventArgs e)
        {
            float ft = 0;
            if (CB_CHKTAX.Checked)
                ft = float.Parse(Drp_PERTAX.SelectedValue) / 100;
            float z = float.Parse(txt_CAMOUT.Text);
            txt_TAMOUT.Text = ((1 + ft) * z).ToString();
            SetCofit();
        }

        protected void Button5_Click(object sender, EventArgs e)
        {
            bool yz = true;
            string mess = "";

            if (Drp_POTYPE.SelectedValue == "一般订单")
            {
                if (txt_CONNUB.Text == "" || txt_VEDNUB.Text == "" || txt_REQTOR.Text == "")
                {
                    yz = false;
                    mess = "请选择合同编号或供应商编号！";
                }
            }

            if (Drp_POTYPE.SelectedValue == "特殊订单")
            {
                if (txt_REMARK.Text == "")
                {
                    yz = false;
                    mess = "该订单为特殊订单，请输入备注信息并且字数不少于10个字！";
                }
                else
                {
                    int len = txt_REMARK.Text.Length;
                    if (len < 10)
                    {
                        yz = false;
                        mess = "输入备注的字数不能少于10个字！";
                    }
                }
            }


            if (yz)
            {
                int returnvalue = 0;
                Proj_Podata PoData = new Proj_Podata();
                if (!string.IsNullOrEmpty(Request["id"]))
                {
                    PoData.ID = int.Parse(Request["id"]);
                    PoData.Attach();
                    PoData.CONNUB = txt_CONNUB.Text;
                    PoData.VENDPO = hf.Text;
                    PoData.VEDNUB = txt_VEDNUB.Text;
                    PoData.REMARK = txt_REMARK.Text;
                    PoData.CHKTAX = CB_CHKTAX.Checked;
                    PoData.CAMOUT = Convert.ToDecimal(txt_CAMOUT.Text);
                    PoData.DLDATE = Convert.ToDateTime(txt_DLDATE.Text);
                    PoData.TAMOUT = Convert.ToDecimal(txt_TAMOUT.Text);
                    PoData.REQTOR = txt_REQTOR.Text;
                    PoData.PERTAX = Convert.ToDecimal(Drp_PERTAX.SelectedValue);
                    // PoData.PERTAX = Convert.ToDecimal(txt_PERTAX.Text);
                    PoData.STATUS = 0;
                    PoData.AddTime = Convert.ToDateTime(txt_AddTime.Text);
                    PoData.PATYPE = Drp_PATYPE.SelectedValue;
                    returnvalue = TbsDbSession.Default.Update<Proj_Podata>(PoData);
                }
                else
                {
                    PoData.DeAttach();
                    PoData.CONNUB = txt_CONNUB.Text;
                    PoData.VENDPO = hf.Text;
                    PoData.VEDNUB = txt_VEDNUB.Text;
                    PoData.REMARK = txt_REMARK.Text;
                    PoData.POTYPE = Drp_POTYPE.SelectedValue;
                    string s = "";
                    if (Drp_POTYPE.SelectedValue == "特殊订单")
                        s = "ST";
                    else
                    {
                        PoData.CAMOUT = Convert.ToDecimal(txt_CAMOUT.Text);
                        PoData.DLDATE = Convert.ToDateTime(txt_DLDATE.Text);
                        PoData.TAMOUT = Convert.ToDecimal(txt_TAMOUT.Text);
                        PoData.PERTAX = Convert.ToDecimal(Drp_PERTAX.SelectedValue);
                        // PoData.PERTAX = Convert.ToDecimal(txt_PERTAX.Text);
                        PoData.CHKTAX = CB_CHKTAX.Checked;
                    }
                    PoData.PONBER = s + DFieldSN.SN(EnumData.DataSNEunm.采购订单号, false);
                    PoData.VENDPO = hf.Text;
                    PoData.REQTOR = txt_REQTOR.Text;
                    PoData.PATYPE = Drp_PATYPE.SelectedValue;
                    PoData.STATUS = 0;
                    PoData.AddTime = Convert.ToDateTime(txt_AddTime.Text);
                    PoData.IsShou = false;
                    returnvalue = TbsDbSession.Default.Insert<Proj_Podata>(PoData);
                }
                if (returnvalue > 0)
                {
                    Alert.Show("更新成功！", "提示", ActiveWindow.GetHideRefreshReference());
                }
            }
            else
            {
                Alert.Show(mess);
            }
        }





        protected void Button6_Click(object sender, EventArgs e)
        {
            UpdateDeliver();
            int id = int.Parse(Request["id"]);
            Proj_Podata vc = new Proj_Podata();
            vc.ID = id;
            vc.Attach();
            vc.STATUS = 1;
            TbsDbSession.Default.Update<Proj_Podata>(vc);

            Alert.Show("审批结束", "提示", ActiveWindow.GetHideRefreshReference());
        }

        protected void Button7_Click(object sender, EventArgs e)
        {
            UpdateDeliver();
            int id = int.Parse(Request["id"]);
            Proj_Podata vc = new Proj_Podata();
            vc.ID = id;
            vc.Attach();
            vc.STATUS = 2;
            TbsDbSession.Default.Update<Proj_Podata>(vc);
            Alert.Show("审批结束", "提示", ActiveWindow.GetHideRefreshReference());
        }



        protected void UpdateDeliver()
        {
            try
            {
                ChanExt.DropDownList ddl = new ChanExt.DropDownList();
                DataBaseHelper.BindDrp(ddl, EnumData.DataBaseEunm.Plan);
                List<Proj_Podata> podataList = TbsDbSession.Default.From<Proj_Podata>().Where(Proj_Podata._.STATUS == 1).ToList();
                foreach (Proj_Podata item in podataList)
                {
                    if (DateTimeDiff.CompareDate(DateTime.Now.ToString(), item.DLDATE.Value.ToString(), 7))
                    {
                        int c = TbsDbSession.Default.From<Proj_Delivery>().Where(Proj_Delivery._.PONBER == item.PONBER).Count();
                        if (c == 0)
                        {
                            Proj_Contat _contat = TbsDbSession.Default.From<Proj_Contat>().Where(Proj_Contat._.CONNUB == item.CONNUB).ToFirst();
                            if (_contat != null)
                            {
                                string _cutno = _contat.CUTNUB;
                                string _cutname = "";
                                Proj_Custor cus = TbsDbSession.Default.From<Proj_Custor>().Where(Proj_Custor._.CUTNUB == _contat.CUTNUB).ToFirst();
                                if (cus != null)
                                    _cutname = cus.CUTNAM;
                                Proj_Delivery Plan = new Proj_Delivery();
                                Plan.DeAttach();
                                Plan.SHPNUB = DFieldSN.SN(EnumData.DataSNEunm.运货计划编号);
                                Plan.PONBER = item.PONBER;
                                Plan.CUTNO = _contat.CUTNUB;
                                Plan.CUTNAM = _cutname;
                                Plan.ADDRES = _contat.ADDRES;// txt_ADDRES.Text;
                                Plan.PLDATE = item.DLDATE.Value;  // Convert.ToDateTime(txt_PLDATE.Text);
                                Plan.STTIME = Convert.ToDateTime(item.DLDATE.Value.ToString("hh:mm"));// Convert.ToDateTime(txt_STTIME.Text);
                                // Plan.EDTIME = Convert.ToDateTime(txt_EDTIME.Text);
                                Plan.CONTET = "";// txt_CONTET.Text;
                                Plan.STATUS = ddl.SelectedValue;// Drp_STATUS.SelectedValue;
                                Plan.COMBIN = false;
                                Plan.REMARK = ""; //txt_REMARK.Text;
                                Plan.Adder = CookInfo.EAdminTrueName();
                                Plan.AddID = CookInfo.EAdminid();
                                Plan.AddTime = DateTime.Now;
                                Plan.EmpName = "";
                                Plan.VEDNNBNo = txt_VEDNNBNo.Text;
                                TbsDbSession.Default.Insert<Proj_Delivery>(Plan);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {

            }
           
        }


    }
}